#!/usr/bin/env python
# -*- coding:utf-8 -*-

from tornado import httpserver, ioloop, web
import random
import torndb



ROOM_INFO = {}
USER_INFO = {}
PLAYER_SETTING = {
	8: {'狼人': 3, '预言家': 1, '女巫': 1, '猎人': 1, '平民': 2},
	9: {'狼人': 3, '预言家': 1, '女巫': 1, '猎人': 1, '平民': 3},
	10: {'狼人': 4, '预言家': 1, '女巫': 1, '猎人': 1, '平民': 3},
	11: {'狼人': 4, '预言家': 1, '女巫': 1, '猎人': 1, '平民': 4},
	12: {'狼人': 4, '预言家': 1, '女巫': 1, '猎人': 1, '平民': 5},
}


class LogInHandler(web.RequestHandler):
	def get(self, *args, **kwargs):
		self.render('login.html')


class IndexHandler(web.RequestHandler):
	def get(self, *args, **kwargs):
		self.render('index.html')

	def post(self, *args, **kwargs):
		user = self.get_argument('user')
		password = self.get_argument('password')
		database = db.query('SELECT * FROM blog WHERE id = %s', user)
		if len(database) == 0:
			db.insert('insert into blog(id,content)values(%s,%s)', user, password)
		else:
			if database[0]['content'] == password:
				self.render('index.html')
			else:
				self.render('login.html')


class CreateGameHandler(web.RequestHandler):
	def post(self, *args, **kwargs):
		player_num = self.get_argument('player_num')
		player_list = []
		player_num = int(player_num)
		player_seting = PLAYER_SETTING[player_num]
		for role in player_seting:
			for i in range(player_seting[role]):
				player_list.append({'role': role,
									'player':'还没加入',
									'person_id': ''})
		random.shuffle(player_list)
		while True:
			room_num = str(random.randint(1, 100))
			if room_num not in ROOM_INFO:
				break
		ROOM_INFO[room_num] = {
			'players': player_list,
			'judge': '房主'
		}
		db.insert('insert into room_info(id,room_num,role,life,all_num)values(%s,%s,%s,%s,%s)', 255, room_num, 255, 255, player_num)
		self.render('game.html', room_num=room_num, player_list=player_list, settings=player_seting)



class JoinGameHandler(web.RequestHandler):
	def post(self, *args, **kwargs):
		join_num = self.get_argument('room_num')
		database = db.query('SELECT * FROM room_info WHERE room_num = %s AND id = %s AND role = %s', join_num, 255, 255)
		data = db.query('SELECT * FROM room_info WHERE room_num = %s AND role != %s', join_num, 255)
		list = []
		if len(data) < database[0]['all_num']:
			for i in range(len(data)):
				list.append(data[i]['role'])
			while True:
				index = random.randint(1, database[0]['all_num'])
				if index not in list:
					break
			role = ''
			if database[0]['all_num'] == 8:
				if index <= 3:
					role = '狼人'
				elif index == 4:
					role = '预言家'
				elif index == 5:
					role = '女巫'
				elif index == 6:
					role = '猎人'
				else:
					role = '平民'
			elif database[0]['all_num'] == 9:
				if index <= 3:
					role = '狼人'
				elif index == 4:
					role = '预言家'
				elif index == 5:
					role = '女巫'
				elif index == 6:
					role = '猎人'
				else:
					role = '平民'
			elif database[0]['all_num'] == 10:
				if index <= 4:
					role = '狼人'
				elif index == 5:
					role = '预言家'
				elif index == 6:
					role = '女巫'
				elif index == 7:
					role = '猎人'
				else:
					role = '平民'
			elif database[0]['all_num'] == 11:
				if index <= 4:
					role = '狼人'
				elif index == 5:
					role = '预言家'
				elif index == 6:
					role = '女巫'
				elif index == 7:
					role = '猎人'
				else:
					role = '平民'
			elif database[0]['all_num'] == 12:
				if index <= 4:
					role = '狼人'
				elif index == 5:
					role = '预言家'
				elif index == 6:
					role = '女巫'
				elif index == 7:
					role = '猎人'
				else:
					role = '平民'
			db.insert('insert into room_info(id,room_num,role,life,all_num)values(%s,%s,%s,%s,%s)', 0, join_num, index, 1, 0)
			USER_INFO = {
				'room_num': join_num,
				'role': role
			}#这里应该换成从数据库中提取数据，join_num直接从post请求中获得，role要先把数据库中所有的这个房间的人取出来，然后从剩下的人物中随机。
			self.render('play.html', user_info=USER_INFO)
		else:
			self.render('full.html')

class RefreshHandler(web.RequestHandler):
	def get(self, num):
		database = db.query('SELECT * FROM room_info WHERE room_num = %s AND id = %s AND role = %s', num, 255, 255)
		player_num = database[0]['all_num']
		player_list = []
		player_num = int(player_num)
		player_seting = PLAYER_SETTING[player_num]
		data = db.query('SELECT * FROM room_info WHERE room_num = %s AND id = %s', num, 0)
		for i in range(database[0]['all_num']):
			if database[0]['all_num'] == 8:
				role = ['狼人', '狼人', '狼人', '预言家', '女巫', '猎人', '平民', '平民']
				player_list.append({'role': role[i], 'player': '还没加入', 'person_id': ''})
			elif database[0]['all_num'] == 9:
				role = ['狼人', '狼人', '狼人', '预言家', '女巫', '猎人', '平民', '平民', '平民']
				player_list.append({'role': role[i], 'player': '还没加入', 'person_id': ''})
			elif database[0]['all_num'] == 10:
				role = ['狼人', '狼人', '狼人', '狼人', '预言家', '女巫', '猎人', '平民', '平民', '平民']
				player_list.append({'role': role[i], 'player': '还没加入', 'person_id': ''})
			elif database[0]['all_num'] == 11:
				role = ['狼人', '狼人', '狼人', '狼人', '预言家', '女巫', '猎人', '平民', '平民', '平民', '平民']
				player_list.append({'role': role[i], 'player': '还没加入', 'person_id': ''})
			elif database[0]['all_num'] == 12:
				role = ['狼人', '狼人', '狼人', '狼人', '预言家', '女巫', '猎人', '平民', '平民', '平民', '平民', '平民']
				player_list.append({'role': role[i], 'player': '还没加入', 'person_id': ''})
		for i in range(len(data)):
			index = data[i]['role']
			if database[0]['all_num'] == 8:
				if index <= 3:
					role = '狼人'
				elif index == 4:
					role = '预言家'
				elif index == 5:
					role = '女巫'
				elif index == 6:
					role = '猎人'
				else:
					role = '平民'
			elif database[0]['all_num'] == 9:
				if index <= 3:
					role = '狼人'
				elif index == 4:
					role = '预言家'
				elif index == 5:
					role = '女巫'
				elif index == 6:
					role = '猎人'
				else:
					role = '平民'
			elif database[0]['all_num'] == 10:
				if index <= 4:
					role = '狼人'
				elif index == 5:
					role = '预言家'
				elif index == 6:
					role = '女巫'
				elif index == 7:
					role = '猎人'
				else:
					role = '平民'
			elif database[0]['all_num'] == 11:
				if index <= 4:
					role = '狼人'
				elif index == 5:
					role = '预言家'
				elif index == 6:
					role = '女巫'
				elif index == 7:
					role = '猎人'
				else:
					role = '平民'
			elif database[0]['all_num'] == 12:
				if index <= 4:
					role = '狼人'
				elif index == 5:
					role = '预言家'
				elif index == 6:
					role = '女巫'
				elif index == 7:
					role = '猎人'
				else:
					role = '平民'
			player_list[index-1] = {'role': role, 'player': '已经进入', 'person_id': data[i]['id']}
		self.render('game.html', room_num=num, player_list=player_list, settings=player_seting)


setting = {
	'template_path': 'template',
	'static_path': 'static',
	'static_url_prefix': '/static/'
}


app = web.Application([
	(r"/", LogInHandler),
	(r"/index", IndexHandler),
	(r"/create_game", CreateGameHandler),
	(r"/join_game", JoinGameHandler),
	(r"/create_game/(?P<num>\d*)", RefreshHandler)
], **setting)


if __name__ == '__main__':
	db = torndb.Connection("127.0.0.1:3306", "test", user="root", password="yang1sheng", time_zone='+8:00')
	# create = 'create table blog(id int,content text)'
	# db.execute(create)
	# create = 'create table room_info(id int,room_num int,role int,life int,all_num int)'
	# db.execute(create)
	# sd = 'blog'
	# sdd = 8
	# sddd = 'Jefrey'
	# id = 'id'
	# content = 'content'
	# db.insert('insert into %s ' % (sd) + '(%s,%s)' % (id, content) + 'values(%s,%s)', sdd, sddd)
	# sql = 'SELECT * FROM blog WHERE content = %s AND id < %s'
	# # 查询到一条数据时为字典
	# database = db.query(sql, 'Jefrey', 11)
	# print(database)
	# print(database[0]['id'])
	#db.execute("delete from room_info ")
	http_server = httpserver.HTTPServer(app)
	http_server.listen(8080)
	ioloop.IOLoop.current().start()
